//
//  FMDBManager.m
//  IFreeAppDemo
//
//  Created by qianfeng on 15/11/6.
//  Copyright © 2015年 qianfeng. All rights reserved.
//

#import "FMDBManager.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"

@implementation FMDBManager
{
    // 线程安全
    FMDatabaseQueue * _queue;
}

+ (id)shareInstance
{
    static dispatch_once_t onceToken;
    static FMDBManager * manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[FMDBManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/IFree.sqlite"];
        NSLog(@"path:%@",path);
        _queue = [FMDatabaseQueue databaseQueueWithPath:path];
        // 创建表
        [_queue inDatabase:^(FMDatabase *db) {
            NSString * sql = @"create table if not exists LimitFree (applicationId integer primary key autoincrement,iconUrl text,categoryName text,currentPrice text,downloads text,expireDatetime text,favorites text,starCurrent text,name text)";
            if(![db executeUpdate:sql]){
                NSLog(@"create table error!");
            }
        }];
    }
    return self;
}

- (void)insertIntoDB:(LimitFreeModel *)model
{
    [_queue inDatabase:^(FMDatabase *db) {
        // FMBD中 基本数据类型都必须转化为NSNumber否则插入会崩溃
        if (![db executeUpdate:@"insert into LimitFree (applicationId,iconUrl,categoryName,currentPrice,downloads,expireDatetime,favorites,starCurrent,name) values (?,?,?,?,?,?,?,?,?)",[NSNumber numberWithInteger:model.applicationId.integerValue],model.iconUrl,model.categoryName,model.currentPrice,model.downloads,model.expireDatetime,model.favorites,model.starCurrent,model.name]) {
            NSLog(@"insert error!");
        }
    }];
}

@end
